<template>
  <div class="app-container home">
    <el-row :gutter="20">
      <el-col :sm="24" :lg="24">
        <h2 class="slogan">欢迎你！尊敬的{{(user.nickName!=null&&user.nickName!='')?user.nickName:user.userName}}{{user.sex!=null?(user.sex==0?'先生':(user.sex==1?'女士':'')):''}}。</h2>  
      </el-col>
    </el-row>
    <el-divider />
    <el-row :gutter="20">
      <el-col :xs="24" :sm="24" :md="12" :lg="12">
        <el-card class="">
          <div id="char1" style="width: 100%;height:500px;">
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="24" :md="12" :lg="12">
        <el-card class="">
          <div id="char2" style="width: 100%;height:500px;">
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
// import { mapState } from 'vuex'
import { getUserProfile } from "@/api/system/user";
import { getPostNumberForDate } from "@/api/forum/post";
import { getReviewNumberForDate } from "@/api/forum/review";
import { getSchoolRankList } from "@/api/forum/school";
import * as echarts from 'echarts';

Date.prototype.format = function (format) {
     var args = {
         "M+": this.getMonth() + 1,
         "d+": this.getDate(),
         "h+": this.getHours(),
         "m+": this.getMinutes(),
         "s+": this.getSeconds(),
         "q+": Math.floor((this.getMonth() + 3) / 3),  //quarter
         "S": this.getMilliseconds()
     };
     if (/(y+)/.test(format))
         format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
     for (var i in args) {
         var n = args[i];
         if (new RegExp("(" + i + ")").test(format))
             format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? n : ("00" + n).substr(("" + n).length));
     }
     return format;
 };

export default {
  name: "Index",
  data() {
    return {
      user: {},
      schoolRankList:[],
      postList: [],
      reviewList: [],
      popularityRankingOption: {//单日学校热度排行（）
        title: {
          text: '单日学校热度排行'
        },
        dataset: {
          source: [
          ]
        },
        grid: { containLabel: true },
        xAxis: { name: 'amount' },
        yAxis: { type: 'category' },
        visualMap: {
          orient: 'horizontal',
          left: 'center',
          min: 10,
          max: 100,
          text: ['High Score', 'Low Score'],
          // Map the score column to color
          dimension: 0,
          inRange: {
            color: ['#65B581', '#FFCE34', '#FD665F']
          }
        },
        series: [
          {
            type: 'bar',
            encode: {
              // Map the "amount" column to X axis.
              x: 'amount',
              // Map the "product" column to Y axis
              y: 'product'
            }
          }
        ]
      },
      postReviewOption : {
        visualMap: [
          {
            show: false,
            type: 'continuous',
            seriesIndex: 0,
            min: 0,
            max: 400
          },
          {
            show: false,
            type: 'continuous',
            seriesIndex: 1,
            min: 0,
            max: 400
          }
        ],
        title: [
          {
            left: 'center',
            text: '最近一周贴子新增变化'
          },
          {
            top: '52%',
            left: 'center',
            text: '最近一周评论新增变化'
          }
        ],
        tooltip: {
          trigger: 'axis'
        },
        xAxis: [
          {
            data: [],
            gridIndex: 0
          },
          {
            data: [],
            gridIndex: 1
          }
        ],
        yAxis: [
          {
            gridIndex: 0,
            axisLabel: {
              formatter: '{value} 条'
            }
          },
          {
            gridIndex: 1,
            axisLabel: {
              formatter: '{value} 条'
            }
          }
        ],
        grid: [
          {
            bottom: '60%'
          },
          {
            top: '60%'
          }
        ],
        series: [
          {
            data: [],
            type: 'line',
            xAxisIndex: 0,
            yAxisIndex: 0
          },
          {
            data: [],
            type: 'line',
            xAxisIndex: 1,
            yAxisIndex: 1
          }
        ],
      }
    };
  },
  computed:{
    // ...mapState("user",["name","id"]),
  },
  created() {
    this.getPostReviewInfo();
    this.getSchoolRankInfo();
    this.getUser();
  },
  mounted(){
  },
  methods: {
    getPostReviewInfo(){
      const date = new Date();
      const stimp = date.getTime();
      var dateList = [];
      for(var i=6; i>=0;i--){
        var temp = new Date(stimp-86400000*i);
        dateList[6-i]= temp.format('yyyy-MM-dd');
      }
      for(var i=0; i<7;i++){
        this.postReviewOption.xAxis[0].data[i] = dateList[i].substr(5);
        this.postReviewOption.xAxis[1].data[i] = dateList[i].substr(5);
      }
      console.log(dateList);
      for(var i=0; i<7;i++){
        getPostNumberForDate(dateList[i]).then(response =>{
          // this.postReviewOption.series[0].data[this.postReviewOption.series[0].data.length]=response.total;
          this.postList[this.postList.length] = { 
            "size" : response.data.size,
            "date" : new Date(response.data.date).getTime()
         }
        })
      }
      for(var i=0; i<7;i++){
        getReviewNumberForDate(dateList[i]).then(response =>{
          // this.postReviewOption.series[1].data[this.postReviewOption.series[1].data.length]=response.total;
          this.reviewList[this.reviewList.length] = { 
            "size" : response.data.size,
            "date" : new Date(response.data.date).getTime()
         }
        })
      }
      // console.log(this.postReviewOption);
      // console.log(this.postList);
      // console.log(this.reviewList);
      setTimeout((myChart)=>{
        // console.log(typeof(this.postList[0].date))
        // var tempDate = new Date(this.postList[0].date)
        // console.log(tempDate.getTime() )
        // console.log(typeof(tempDate))
        this.sort(this.postList);
        this.sort(this.reviewList);
        // console.log(this.postList);
        // console.log(this.reviewList);
        for(var i=0;i<this.postList.length;i++){
          this.postReviewOption.series[0].data[i] = this.postList[i].size;
          this.postReviewOption.series[1].data[i] = this.reviewList[i].size;
        }
        var myChart = echarts.init(document.getElementById('char1'));
        myChart.setOption(this.postReviewOption);
      }, 2000);

    },
    sort(list){
      for(var i=0;i<list.length;i++){
        for(var x=0;x<list.length - i - 1;x++){
          if(list[x].date > list[x+1].date){
            var temp = list[x];
            list[x] = list[x+1];
            list[x+1] = temp;
          }
        }
      }
      return list;
    },
    getSchoolRankInfo() {
      var date = new Date();
      var query = {
        "date": date.format('yyyy-MM-dd hh:mm:ss')
      }
      getSchoolRankList(query).then(response => {
        if(response.rows.length<=10){
          this.schoolRankList = response.rows;
        }else{
          for(var i=0;i<10;i++){
            this.schoolRankList[i] = response.rows[i];
          }
        }
      });
      var colorList = [89.3, 57.1, 74.4, 50.1, 89.7, 68.1, 19.6, 10.6, 32.7,95.2];

      setTimeout((myChart)=>{
        var temp = []
        temp[0] = ['score', 'amount', 'product'];
        for(var i=1;i<=this.schoolRankList.length;i++){
          temp[i] = [colorList[i-1], this.schoolRankList[i-1].rank, this.schoolRankList[i-1].schoolName]
        }
        this.popularityRankingOption.dataset.source = temp;
        if(this.schoolRankList.length==0){
          this.popularityRankingOption.title.text="今日论坛暂无人员活动"
        }
        var myChart = echarts.init(document.getElementById('char2'));
        myChart.setOption(this.popularityRankingOption);
      }, 2000);
    },
    getUser() {
      getUserProfile().then(response => {
        this.user = response.data;
      });
    },
    goTarget(href) {
      window.open(href, "_blank");
    }
  }
};
</script>

<style scoped lang="scss">
.home {
 .slogan{
  color: #73c0de;
 }
}
</style>


